#include "tokenizer.h"

char *line_buffer;
const char delimiters[] = " \t\n";	
int zero_flag = 0;

char *trimwhitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace(*str)) str++;

  //while(!isdigit(*str)) str++;


  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace(*end)) end--;

  // Write new null terminator
  *(end+1) = 0;

  return str;
}


void tokenizer_strtoupper(char **str)
{
	char *str_ptr;
			
	for(str_ptr = *str; *str_ptr != '\0'; str_ptr++)
		*str_ptr = toupper(*str_ptr);
}

int tokenizer_zero_token(){
	return(zero_flag);
}

int tokenizer_read_name(char **name){	
	
	char *token;
	
	if ((token = strtok (line_buffer, delimiters)) == NULL) 
		return(-1);

	tokenizer_strtoupper(&token);
	*name = strdup(token);
	
	return(strlen(token));
}

int tokenizer_read_node(char **node){	
	
	char *token;
		
	if ( (token = strtok (NULL, delimiters)) == NULL )
		return(-1);

	trimwhitespace(token);
	tokenizer_strtoupper(&token);
	*node = strdup(token);
	
	if(	atoi(token) == 0)	//vrika 0 kombo
		zero_flag = 1;

	return(strlen(token));
}

int tokenizer_read_value(double *value){
	
	char *token, *endptr;
	int errno;
	double val;

	if ((token = strtok (NULL, delimiters)) != NULL){
		
		trimwhitespace(token);
		errno = 0;
		val = strtod(token, &endptr);
				
		
		/* Error checking code */
		if ((errno == ERANGE && (val == HUGE_VAL || val == HUGE_VALF) || (val == HUGE_VALL))
                   || (errno != 0 && val == 0)) {
				perror("strtod");
				exit(42);
		}

		if (endptr == token) {
			fprintf(stderr, "Error: No digits were found\n");
			printf("(%s)\n", token);
			exit(42);
		}
		
		//Elegxos gia perasma regexp kai oxi arithmou
		if (!isspace(*endptr) && (*endptr) != '\0'){
			printf("Error: Dont enter expessions, just Digits for value: (%s)\n", token);
			exit(42);
		}
		
		//all ok
		
		*value = val;
		
			
	}
}

int tokenizer_read_option(char **option){	
	
	char *token;
		
	if ((token = strtok (NULL, delimiters)) == NULL )
		return(0);

	trimwhitespace(token);	
	tokenizer_strtoupper(&token);
	*option = strdup(token);
	return(strlen(token));
}




